<template>
  <div v-loading="loading" element-loading-text="加载中..." class="code_strategy">
    <div class="btn_container">
      <HPlainButton @click="saveSet(formRef1, formRef2)">保存</HPlainButton>
    </div>
    <div class="form_container">
      <el-form
        ref="formRef1"
        :model="form"
        class="left"
        :rules="rules"
        label-width="110"
        inline-message
      >
        <el-form-item label="条码规则">
          <el-radio-group v-model="form.ruleType">
            <el-radio :value="1">数字+字母组合</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="prefix">
          <el-form-item label="条码规格前缀" prop="codePrefix">
            <el-input
              v-model.trim="form.codePrefix"
              clearable
              maxlength="2"
              placeholder="前缀名称"
            />
          </el-form-item>
          <el-form-item label=" " class="checkbox_container" prop="codeRule">
            <el-checkbox-group v-model="form.codeRule">
              <el-checkbox value="1">六位产品生产日期</el-checkbox>
              <el-checkbox value="2">八位防伪码</el-checkbox>
              <el-checkbox value="3">六位随机防窜码</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
        <div class="prefix">
          <el-form-item label="临时规格前缀" prop="temporaryPrefix">
            <el-input
              v-model.trim="form.temporaryPrefix"
              maxlength="2"
              clearable
              placeholder="前缀名称"
            />
          </el-form-item>
          <el-form-item label=" " class="checkbox_container" prop="temporRule">
            <el-checkbox-group v-model="form.temporRule">
              <el-checkbox value="1">六位产品生产日期</el-checkbox>
              <el-checkbox value="2">八位防伪码</el-checkbox>
              <el-checkbox value="3">六位随机防窜码</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
        <div class="prefix">
          <el-form-item label="仓储条码前缀" prop="storehousePrefix">
            <el-input
              v-model.trim="form.storehousePrefix"
              maxlength="2"
              clearable
              placeholder="前缀名称"
            />
          </el-form-item>
          <el-form-item label=" " class="checkbox_container" prop="storehouseRule">
            <el-checkbox-group v-model="form.storehouseRule">
              <el-checkbox value="1">六位产品生产日期</el-checkbox>
              <el-checkbox value="2">八位防伪码</el-checkbox>
              <el-checkbox value="3">六位随机防窜码</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
      </el-form>
      <el-form
        ref="formRef2"
        :model="form"
        :rules="rules"
        label-width="80"
        class="right"
        inline-message
      >
        <el-form-item label="条码导入">
          <el-radio-group v-model="form.enableImport">
            <el-radio :value="true">启用</el-radio>
            <el-radio :value="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="仓储条码">
          <el-radio-group v-model="form.enableStorehouseCode">
            <el-radio :value="true">启用</el-radio>
            <el-radio :value="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="批次前缀" prop="batchPrefix">
          <el-input
            v-model.trim="form.batchPrefix"
            clearable
            maxlength="2"
            placeholder="前缀名称"
          />
        </el-form-item>
        <el-form-item label="导入前缀" prop="importPrefix">
          <el-input
            v-model.trim="form.importPrefix"
            clearable
            maxlength="2"
            placeholder="前缀名称"
          />
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import { getCodeSet, saveCodeSet } from '@/api/basic'

  const loading = ref(false)
  const form = reactive({
    id: null,
    ruleType: 1,
    codePrefix: '',
    codeRule: [],
    temporaryPrefix: '',
    temporRule: [],
    enableStorehouseCode: true,
    storehousePrefix: '',
    storehouseRule: [],
    enableImport: true,
    importPrefix: '',
    batchPrefix: '',
  })

  // 表单元素
  const formRef1 = ref<FormInstance>()
  const formRef2 = ref<FormInstance>()

  // 验证规则
  const rules = reactive({
    codePrefix: [
      { required: true, message: '请输入前缀', trigger: 'blur' },
      {
        pattern: /^[A-Za-z1-9]{1,2}$/,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
    codeRule: [
      { required: true, message: '请选择组合类型', trigger: 'blur' },
      {
        validator: (rule, value: string, callback) => {
          if (form.codeRule.length < 2) {
            callback(new Error('至少选择两种组合类型'))
          } else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
    temporaryPrefix: [
      { required: true, message: '请输入前缀', trigger: 'blur' },
      {
        pattern: /^[A-Za-z1-9]{1,2}$/,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
    temporRule: [
      { required: true, message: '请选择组合类型', trigger: 'blur' },
      {
        validator: (rule, value: string, callback) => {
          if (form.temporRule.length < 2) {
            callback(new Error('至少选择两种组合类型'))
          } else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
    storehousePrefix: [
      { required: true, message: '请输入前缀', trigger: 'blur' },
      {
        pattern: /^[A-Za-z1-9]{1,2}$/,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
    storehouseRule: [
      { required: true, message: '请选择组合类型', trigger: 'blur' },
      {
        validator: (rule, value: string, callback) => {
          if (form.storehouseRule.length < 2) {
            callback(new Error('至少选择两种组合类型'))
          } else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
    batchPrefix: [
      { required: true, message: '请输入前缀', trigger: 'blur' },
      {
        pattern: /^[A-Za-z1-9]{1,2}$/,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
    importPrefix: [
      { required: true, message: '请输入前缀', trigger: 'blur' },
      {
        pattern: /^[A-Za-z1-9]{1,2}$/,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
  })
  // 获取条码设置
  const getSet = async () => {
    loading.value = true
    await getCodeSet().then((res) => {
      form.id = res.data.data.row.id
      form.ruleType = res.data.data.row.ruleType
      form.codePrefix = res.data.data.row.codePrefix
      form.codeRule = res.data.data.row.codeRule.split(',')
      form.temporaryPrefix = res.data.data.row.temporaryPrefix
      form.temporRule = res.data.data.row.temporRule.split(',')
      form.enableStorehouseCode = res.data.data.row.enableStorehouseCode
      form.storehousePrefix = res.data.data.row.storehousePrefix
      form.storehouseRule = res.data.data.row.storehouseRule.split(',')
      form.enableImport = res.data.data.row.enableImport
      form.importPrefix = res.data.data.row.importPrefix
      form.batchPrefix = res.data.data.row.batchPrefix
    })
    loading.value = false
  }

  // 保存条码设置
  const saveSet = (formEl: FormInstance | undefined, formEl2: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        formEl2.validate((valid2) => {
          if (valid2) {
            const data = {
              batchPrefix: form.batchPrefix,
              codePrefix: form.codePrefix,
              codeRule: form.codeRule.join(),
              enableImport: form.enableImport,
              enableStorehouseCode: form.enableStorehouseCode,
              id: form.id,
              importPrefix: form.importPrefix,
              ruleType: form.ruleType,
              storehousePrefix: form.storehousePrefix,
              storehouseRule: form.storehouseRule.join(),
              temporRule: form.temporRule.join(),
              temporaryPrefix: form.temporaryPrefix,
            }
            ElMessageBox({
              type: 'warning',
              title: '提示',
              message: `确认保存修改的设置?`,
              showCancelButton: true,
              closeOnClickModal: false,
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                  instance.confirmButtonLoading = true
                  instance.confirmButtonText = '加载中...'
                  setTimeout(() => {
                    done()
                    setTimeout(() => {
                      instance.confirmButtonLoading = false
                    }, 0)
                  }, 1000)
                } else {
                  done()
                }
              },
            }).then(async () => {
              await saveCodeSet(data).then((res) => {
                if (res.data.success) {
                  ElMessage({
                    message: res.data.message,
                    type: 'success',
                    duration: 5000,
                    plain: true,
                    showClose: true,
                  })
                } else {
                  ElMessage({
                    message: res.data.message,
                    type: 'warning',
                    duration: 5000,
                    plain: true,
                    showClose: true,
                  })
                }
              })
              getSet()
            })
          } else {
            return
          }
        })
      } else {
        return
      }
    })
  }

  // 返回方法
  defineExpose({ getSet })
</script>

<style scoped lang="scss">
  .code_strategy {
    height: 100%;

    .btn_container {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 12px;
    }

    .form_container {
      display: flex;
      column-gap: 108px;
      flex-wrap: wrap;

      :deep(.el-form) {
        display: flex;
        flex-direction: column;
        row-gap: 12px;

        .prefix {
          display: flex;
          column-gap: 24px;

          .checkbox_container {
            .el-form-item__label {
              display: none;
            }
          }
        }

        .el-form-item {
          .el-form-item__label {
            height: 28px;
            line-height: 28px;
          }

          .el-form-item__content {
            display: flex;
            flex-direction: column;
            align-items: flex-start;

            .el-form-item__error {
              margin: 0;
            }

            .el-checkbox-group {
              .el-checkbox {
                height: 27px;
              }
            }

            .el-radio-group {
              .el-radio {
                height: 28px;

                .el-radio__label {
                  height: 28px;
                  line-height: 28px;
                }
              }
            }

            .el-input {
              width: 180px;
            }
          }
        }
      }
    }
  }
</style>
